package com.bmob.lover.app.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.theone.common.ext.DateExtKt;
import com.theone.common.util.DateFormatUtils;
import com.bmob.lover.R;
import com.bmob.lover.data.model.bean.Lover;
import com.bmob.lover.data.model.bean.TheFile;
import com.theone.mvvm.core.app.util.FileDirectoryManager;
import com.theone.mvvm.core.ui.binding_adapter.CoreBindAdapter;

import java.io.File;
import java.util.Objects;

/**
 * @author theone
 */
public class LoverVideoPlayer extends StandardGSYVideoPlayer {

    private static final String TAG = "LoverVideoPlayer";

    ImageView mCoverImage, ivIcon;
    DouYinLoadingView mLoadingView;
    ViewGroup mTimeLayout;

    private TextView tvLocation, tvNickName, tvContent, tvTime;
    private int mContentVisible;
    private boolean isClickPause = false;
//    private ObjectAnimator mProgressAnimator;
//    private int curProgress;

    public LoverVideoPlayer(Context context) {
        super(context);
    }

    public LoverVideoPlayer(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void init(Context context) {
        super.init(context);
        setAutoFullWithSize(false);
        setReleaseWhenLossAudio(true);
        setIsTouchWiget(false);
        setLooping(true);
        setNeedShowWifiTip(false);
        setRotateViewAuto(true);
        setLockLand(false);
        setReleaseWhenLossAudio(false);
        tvLocation = findViewById(R.id.tv_location);
        tvNickName = findViewById(R.id.tv_nickname);
        tvContent = findViewById(R.id.tv_content);
        tvTime = findViewById(R.id.tv_time);
        ivIcon = findViewById(R.id.iv_icon);
        mCoverImage = (ImageView) findViewById(R.id.thumbImage);
        mLoadingView = (DouYinLoadingView) findViewById(R.id.loading_view);
        mTimeLayout = (ViewGroup) findViewById(R.id.time_layout);
        setSpeed(1.0f);

//        mProgressAnimator = ObjectAnimator.ofInt(this, "progress", 0);
    }

    @SuppressLint("SetTextI18n")
    public void setVideoData(Lover lover) {
        tvLocation.setText(lover.getUserAddress());
        tvNickName.setText("@" + lover.getAuthor().getNickname());
        tvContent.setText(lover.getContent());
        mContentVisible = TextUtils.isEmpty(lover.getContent()) ? GONE : VISIBLE;
        tvContent.setVisibility(mContentVisible);
        long date = DateExtKt.formatLong(Objects.requireNonNull(lover.getCreatedAt()), DateExtKt.YYYY_MM_DD_HH_MM_SS);
        tvTime.setText(DateFormatUtils.formatTimeStampString(getContext(), date, DateFormatUtils.FORMAT_TYPE_PERSONAL_FOOTPRINT));
        CoreBindAdapter.imageUrl(ivIcon, lover.getAuthor().getAvatar(), null);

        TheFile file = lover.getFiles().get(0);
        loadCoverImage(file);
        mPlayTag = file.getImageUrl();
        setUpLazy(file.getPath(), true, new File(FileDirectoryManager.INSTANCE.getVideoPath()), null, "");
    }

    private void loadCoverImage(TheFile file) {
        Glide.with(getContext())
                .load(file.getThumbnail())
                .transition(new DrawableTransitionOptions().crossFade())
                .apply(new RequestOptions()
                        .placeholder(R.drawable.image_snap_loading_bg)
                        .override(file.getWidth(), file.getHeight())
                        .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                )
                .into(mCoverImage);
    }

    public void setOnIconClickListener(OnClickListener listener) {
        ivIcon.setOnClickListener(listener);
    }

    @Override
    public int getLayoutId() {
        return R.layout.item_video_player_layout;
    }

    protected void setViewShowState(int visibility, View... views) {
        for (View view : views) {
            setViewShowState(view, visibility);
        }
    }

//    @Override
//    protected void setProgressAndTime(int progress, int secProgress, int currentTime, int totalTime, boolean forceChange) {
//        if (mGSYVideoProgressListener != null && mCurrentState == CURRENT_STATE_PLAYING) {
//            mGSYVideoProgressListener.onProgress(progress, secProgress, currentTime, totalTime);
//        }
//        if (mProgressBar == null || mTotalTimeTextView == null || mCurrentTimeTextView == null) {
//            return;
//        }
//        if (mHadSeekTouch) {
//            return;
//        }
//        if (getGSYVideoManager().getBufferedPercentage() > 0) {
//            secProgress = getGSYVideoManager().getBufferedPercentage();
//        }
//        setSecondaryProgress(secProgress);
//        if (progress == 0) {
//            setProgress(0);
//            return;
//        }
//        if (progress > 94) {
//            progress = 100;
//        }
//        mTotalTimeTextView.setText(CommonUtil.stringForTime(totalTime));
//        if (currentTime > 0) {
//            mCurrentTimeTextView.setText(CommonUtil.stringForTime(currentTime));
//        }
//        if (mBottomProgressBar != null) {
//            setSecondaryProgress(secProgress);
//        }
//        if (progress != 0 || forceChange) {
//            if(curProgress>progress){
//                curProgress = 0;
//            }
//            mProgressAnimator.setIntValues(curProgress, progress);
//            mProgressAnimator.start();
//            curProgress = progress;
//        }
//    }
//
//    @Keep
//    public void setProgress(int progress) {
////        if (progress == mBottomProgressBar.getMax() && isLooping()) {
////            progress = 0;
////        }
//        if (null != mBottomProgressBar) {
//            mBottomProgressBar.setProgress(progress);
//        }
//        if (null != mProgressBar && !mTouchingProgressBar) {
//            mProgressBar.setProgress(progress);
//        }
//    }


    @Override
    protected void hideAllWidget() {
        Log.e(TAG, "hideAllWidget: ");
        cancelDismissControlViewTimer();
    }

    @Override
    protected void changeUiToNormal() {
        Log.e(TAG, "changeUiToNormal: ");
        super.changeUiToNormal();
        setViewShowState(INVISIBLE, mProgressBar, mTimeLayout, mStartButton);
        mTextureViewContainer.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.qmui_config_color_transparent));
        setViewShowState(mBottomProgressBar, VISIBLE);
        tvContent.setVisibility(mContentVisible);
    }

    @Override
    protected void changeUiToPreparingShow() {
        Log.e(TAG, "changeUiToPreparingShow: ");
        setViewShowState(VISIBLE, mLoadingView, mBottomContainer);
        setViewShowState(INVISIBLE, mBottomProgressBar, mProgressBar, mTimeLayout);
        mLoadingView.start();
    }

    @Override
    protected void changeUiToPlayingClear() {
        Log.e(TAG, "changeUiToPlayingClear: ");
        setViewShowState(VISIBLE, mProgressBar, mTimeLayout, mStartButton);
        setViewShowState(INVISIBLE, mBottomContainer, mBottomProgressBar, mLoadingView);
    }

    @Override
    protected void changeUiToPlayingShow() {
        Log.e(TAG, "changeUiToPlayingShow: ");
        if (isClickPause) {
            isClickPause = false;
            if (mTimeLayout.getVisibility() == VISIBLE) {
                updateStartImage();
                return;
            }
        }
        super.changeUiToPlayingShow();
        mLoadingView.stop();
        setViewShowState(VISIBLE, mBottomContainer, mBottomProgressBar);
        tvContent.setVisibility(mContentVisible);
        setViewShowState(INVISIBLE, mStartButton, mLoadingView, mTimeLayout, mProgressBar);
        // 封面一直是存在的，这样不会因为封面的消失而视频播放界面还没出现时出现的黑屏现象
        // 有时会存在封面的尺寸和视频的尺寸不一致，视频之后还能看见封面，所以这个时候要延时将播放界面背景设置成黑色
        postDelayed(() ->
                        mTextureViewContainer.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.black))
                , 500);

    }

    @Override
    protected void changeUiToPauseShow() {
        Log.e(TAG, "changeUiToPauseShow: ");
        setViewShowState(VISIBLE, mStartButton);
        updateStartImage();
        updatePauseCover();
        isClickPause = true;
    }

    @Override
    protected void changeUiToPlayingBufferingShow() {
        Log.e(TAG, "changeUiToPlayingBufferingShow: ");
        super.changeUiToPlayingBufferingShow();
        setViewShowState(INVISIBLE, mBottomProgressBar, mProgressBar);
        setViewShowState(VISIBLE, mLoadingView);
        mLoadingView.start();
    }

    @Override
    protected void changeUiToPlayingBufferingClear() {
        Log.e(TAG, "changeUiToPlayingBufferingClear: ");
        super.changeUiToPlayingBufferingClear();
        setViewShowState(VISIBLE, mBottomProgressBar);
    }

}
